
faApp.controller('PEVCProductListCtrl',['$scope','productService','$location','$controller','$route','$routeParams','sessionService',function($scope,productService,$location,$controller,$route,$routeParams,sessionService) {   
  $controller('ProductBaseCtrl', {$scope: $scope}); 
  
  $scope.ctrlName = "PEVCProductListCtrl";
  $controller('BaseListCtrl', {$scope: $scope}); 

  $scope.products = [];
  $scope.loading = true;
  //获取页面类型，06 pevc
  $scope.t = $routeParams.t;

  // 判断当前用户是否有编辑产品解析报告的权限
  $scope.isAnalytics = false;

  var hasPage = 'hasPagePEVCProductListCtrl';

  angular.forEach(sessionService.getItem("user.access","").split(","), function(o){
    if(o == 'deepAnalyticsDetail.shtml' || o == 'all'){
      $scope.isAnalytics = true;
    }
  });

  $scope.changeProductType = function(){
    var tmp = "";
    $("[name='ptype']").each(function(){
      if($(this).attr("checked") == "checked"){
        tmp += $(this).val() + ",";
      }
    });
    if(tmp.length > 0){
      tmp = tmp.substring(0, tmp.length - 1);
    }else{
      //如果神马都没选，则还是显示默认页面类型
      tmp = $routeParams.t;
    }
    $scope.t = tmp;
    $scope.config['pTypeList'] = tmp;
  };

  $scope.$watch('config',function(){
    //根据页面传入的信托、资管类型，PE/VC,添加查询条件
    if($scope.t != undefined){
      //$scope.searchMap.pType = $scope.t;
      $scope.config['pTypeList'] = $scope.t;
    }
    //$scope.config['pTypeList'] ="06";//pevc固定查询06

    productService.queryProductList($scope.config).then(function(json){
      $scope.products = json.list;
      $scope.pager = json.projectDTO;
      $scope.loading = false;
    });
  },true);
  
  $scope.searchMap['orderBy'] = $routeParams.orderBy || '',
  $scope.searchMap['orderByTag'] = $routeParams.orderByTag || '',
  $scope.config['orderBy'] = $routeParams.orderBy || '',
  $scope.config['orderByTag'] = $routeParams.orderByTag || '',
  
  $scope.changeWeightMap = {};
  $scope.productWeightMap = {};
  $scope.showChangeWeight = function(id){
    if (!$scope.hasAuth("btn","PRODUCT_RECOMMEND")){
      return;
    }
    
    $scope.changeWeightMap[id] = true;
  };
  $scope.changeWeight = function(id){
    productService.productRecommend({fpProjectId:id,recommendWeight:$scope.productWeightMap[id]}).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        $scope.alertNextPage("修改推荐状态成功！");
        $route.reload();
      }
    });
  };

  $scope.orderbyPositionMap = {};
  if (!$routeParams.orderBy && !$routeParams.orderByTag){
    $scope.orderbyPositionMap['weight'] = "0";
  }else{
    $scope.orderbyPositionMap[$routeParams.orderBy] = "0";
  }
  $scope.orderbyFreqMap = {"id":["desc","asc"],"weight":["desc"],"updateDate":["desc","asc"]};

  $scope.orderby = function(field){
    var freq = $scope.orderbyFreqMap[field];
    var old = $scope.orderbyPositionMap[field];
    $scope.orderbyPositionMap = {};
    if (old == undefined){
      $scope.orderbyPositionMap[field] = 0;
    }else{
      $scope.orderbyPositionMap[field] = old + 1;
      if ($scope.orderbyPositionMap[field] >= freq.length){
        $scope.orderbyPositionMap[field] = 0;
      }
    }
    if (field == "weight"){
      $scope.config.orderBy = "";
      $scope.config.orderByTag = "";
    }else{
      $scope.config.orderBy = field;
      $scope.config.orderByTag = freq[$scope.orderbyPositionMap[field]];
    }
  };

  $scope.chkProjectAll = function(){
    if($("#chkProjectAll").attr("checked") == "checked"){
      $("[name='chkProject']").attr("checked","checked");
    }else{
      $("[name='chkProject']").attr("checked",false);
    }
  }

  $scope.sendEmail = function(){
    var allCheck = $("[name='chkProject']");
    var pids = "";
    var firstVal = "";
    var isFirst = 0;
    var error = "";
    $("[name='chkProject']").each(function(){
      if($(this).attr("checked") == "checked"){
        if($(this).attr("accessId") == undefined || $(this).attr("accessId") == ""){
          error += "产品未选择供应方，产品ID：" + $(this).val() + "！\n";
          return false;
        }else{
          if(isFirst == 0){
            isFirst = 1;
            firstVal = $(this).attr("accessId") || "-1";
          }else{
            if(firstVal != $(this).attr("accessId")){
              error = "所选产品不属于同一供应方！";
              return false;
            }
          }
          pids += $(this).val() + ",";
        }
      }
    });
    if(error.length > 0){
      alert(error);
      return;
    }
    if(pids.length > 0){
      if(!confirm("确认发送吗?")){
        return;
      }

      pids = pids.substring(0, pids.length - 1);
      productService.sendEmail(pids).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          alert("发送成功！");
          $scope.alertNextPage("发送成功！");
        }
    });
    }else{
      alert("请选择一个产品！");
    }
  };

  $scope.isShowCopyTypeLayer = false;
  $scope.copyId = "";
  $scope.pt = "";
  $scope.isCopyReport = false;

  $scope.showCopyTypeLayer = function(id,pt){
    $scope.isShowCopyTypeLayer = true;
    $scope.copyId = id;
    $scope.pt = pt;
  }

  $scope.search = function(notsave){
    angular.forEach($scope.searchMap,function(o,i){
      $scope.config[i] = ( undefined == $scope.searchMap[i] ? "" : $scope.searchMap[i]);
    });

    var p = sessionService.getItem(hasPage) || 0;
    if(p > 0){
      $scope.config.pageNo = p;
      sessionService.removeItem(hasPage);
    }else{
      $scope.config.pageNo = 1;
    }

    !notsave && $scope.saveLastSearchConfig();
  };

  $scope.toViewPage = function(id, address){
    if(id){
      sessionService.setItem(hasPage, $scope.pager.pageNo);

      var url = address + 'id=' + id + '&t=' + $scope.t;
      $location.url(url);
    }
  }

  $scope.getLastSearchConfig();
  $scope.search();

}]);

faApp.controller('PEVCProductAddCtrl',['$scope', 'productService','reportService','$location','$controller','$timeout','companyService','supplierService','$route','$filter','$routeParams',function($scope,productService,reportService,$location,$controller,$timeout,companyService,supplierService,$route,$filter,$routeParams) {   
  $controller('BaseCtrl', {$scope: $scope});

  //$scope.product = {pMinimumAmountTmp:100,pRealSubscriptionAmount:0,pRealSubscriptionShare:0,pType:"05",pInvestType:"01",pPublicArea:"00",pSaleStatus:"03",pPaymentInterestType:"03",pEndEarlyIdentification:"0",pProgressiveAmountTmp:10,fpCorpId:0,fpProjectCorpType:'02'};
  $scope.product = {pMinimumAmountTmp:100,pProgressiveAmountTmp:10,pType:"06",pSaleStatus:"02",pRealSubscriptionAmount:0,pRealSubscriptionShare:0,fpCorpId:0,fpProjectCorpType:'02'};
  $scope.loading = true; 

  $scope.pathText = "新增股权基金产品";
  if($routeParams.id){
    $scope.pathText = "修改股权基金产品"; 
  }
  $scope.outproduct={};
  if($routeParams.outProductId!=undefined){
    $scope.product.outProductId=$routeParams.outProductId;
  }
 if($routeParams.productName!=undefined){
    $scope.product.pName=$routeParams.productName;
    $scope.product.pFullName=$routeParams.productName;
  }
  //默认能竞价
  $scope.product.flagBidding=true;
  
  $scope.pPublicAreaModel = $scope.publicAreaModel;
  if ($scope.pPublicAreaModel[0].value != "00")$scope.pPublicAreaModel.unshift({value:"00",text:"全国"});
  $scope.companys = [];
  $scope.companysMap = {};
  $scope.pid = $routeParams.id;

  $scope.supplierListOfProduct = [];
  $scope.accessNameOfCompany = "";

  $scope.t = $routeParams.t;

  // 复制产品时，是否同时复制产品解析报告
  $scope.ct = $routeParams.ct;

  // 复制年化及佣金的数据
  $scope.projectAnnualRevenue = [];
  $scope.projectRabateList = [];
  $scope.attachs = [];

  // 复制产品解析报告
  $scope.report = {};

  $scope.allTjzls = {};

  if($scope.pid != undefined && $scope.pid.length > 0){
    //如果有值，则说明是点了复制按钮，则根据ID加载产品
    productService.productQuery($scope.pid).then(function(json){
      $scope.product = json.project;
      $scope.product.pLinkCode = $scope.product.pCode;
      $scope.product.pIssuingScaleTmp = $scope.product.pIssuingScale / 100000000;
      $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale / 100000000;
      $scope.product.pProgressiveAmountTmp = $scope.product.pProgressiveAmount / 10000;
      $scope.product.pMinimumAmountTmp = $scope.product.pMinimumAmount / 10000;
      $scope.product.pSaleTimeStartStr = $filter("date")($scope.product.pSaleTimeStart,"yyyy-MM-dd");
      $scope.product.image = $scope.product.pImageUri;
      $scope.product.fpCorpId = "0";
      $scope.product.fpProjectCorpType = "02";
      if($scope.product.tjzls!=undefined){
        angular.forEach($scope.product.tjzls.split(","),function(o){
          $scope.allTjzls[o] = true;  
        }); 
      }
      //PE/VC新增扩展字段
      if($scope.product.projectExpandDTO!= undefined){
          $scope.product.peManageOrg=$scope.product.projectExpandDTO.peManageOrg;
          $scope.product.peOrganizeShape=$scope.product.projectExpandDTO.peOrganizeShape;
          $scope.product.peFundShape=$scope.product.projectExpandDTO.peFundShape;
          $scope.product.peSubscriptionFee=$scope.product.projectExpandDTO.peSubscriptionFee;
          $scope.product.peManagementExpense=$scope.product.projectExpandDTO.peManagementExpense;
          $scope.product.peLogoUri=$scope.product.projectExpandDTO.peLogoUri;
          $scope.product.peHomeLogoUri=$scope.product.projectExpandDTO.peHomeLogoUri;
          $scope.product.peRevenueSharing=$scope.product.projectExpandDTO.peRevenueSharing;
          $scope.product.peCompanyDescription=$scope.product.projectExpandDTO.peCompanyDescription;
          delete $scope.product.projectExpandDTO;
      }
    

      // 复制年化及佣金的数据  
      $scope.projectAnnualRevenue = json.projectAnnualRevenueList;
      $scope.projectRabateList = json.projectRabateList;

      delete $scope.product.pSaleTimeStart;
      delete $scope.product.pSaleTimeEnd;
      delete $scope.product.pEstablishmentTime;
      delete $scope.product.pCode;

      $scope.product.pRealSubscriptionAmount = 0;
      $scope.product.pRealSubscriptionShare = 0;
      //delete $scope.product.pRealSubscriptionAmount;
      //delete $scope.product.pRealSubscriptionShare;


      //复制不需要复制销售进度
      delete $scope.product.pPeriods;
      delete $scope.product.pIssuingScale;
      delete $scope.product.pAllSubscriptionAmountTmp;
      delete $scope.product.pRecruitmentSummary;
      $scope.product.pSaleStatus='03';//复制默认为募集中

    });

    // 加载原产品附件的数据 
    productService.productAttachList($scope.pid).then(function(json){
      $scope.attachs = json.projectAttachmentsList;
    });

    // 如果选择复制 产品解析报告，则在此处先加载原产品的解析报告
    if($scope.ct){
      reportService.deepAnalyticsDetail($scope.pid).then(function(json){
        if(json.dto){
          $scope.report = json.dto || {};
          delete $scope.report.fpProductId;
          delete $scope.report.fpProductStatus;
          // delete $scope.report.id;
        }
      });
    }
  }

  companyService.companyList().then(function(json){
    $scope.companys = json.list;
    angular.forEach($scope.companys,function(o){
      $scope.companysMap[o.id] = o;  
    });
  });

$scope.queryAccessCompany="";
  $scope.$watch('queryAccessCompany',function(){
     supplierService.supplierList({accessCompany:$scope.queryAccessCompany}).then(function(json){
        $scope.supplierListOfProduct = json.list;
      });
  },true);

  //$scope.product.pSummary = "<p class='p-c-title'><span style='font-family: 微软雅黑;font-size: 16px;'><a name='mjzh'></a>募集账号：</span></p><p class='p-c-title'><span style='font-family: 微软雅黑; font-size: 16px;'><a name='cpys'></a>产品优势：</span></p><p class='p-c-title'><span style='font-family: 微软雅黑; font-size: 16px;'><a name='fxkz'></a>风险控制：</span></p><p class='p-c-title'><span style='font-family: 微软雅黑; font-size: 16px;'><a name='hkly'></a>还款来源：</span></p><p class='p-c-title'><span style='font-family: 微软雅黑; font-size: 16px;'><a name='zjyt'></a>资金用途：</span></p><p class='p-c-title'><span style='font-family: 微软雅黑; font-size: 16px;'><a name='rzf'></a>融资方：</span></p><p class='p-c-title'><span style='font-family: 微软雅黑; font-size: 16px;'><a name='dbf'></a>担保方：</span></p>";

  $scope.product.pSummary = "<div style='width:1000px;'><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='mjzh'></a>募集账号</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='xmld'></a>项目亮点</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='fxkz'></a>风险控制</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='zjyt'></a>资金用途</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='gltd'></a>管理团队</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='tzcl'></a>投资策略</li><li style=''>---输入内容---</li></ul><ul style='width:100%; margin: 0px; padding: 0px;'><li style='height: 40px;line-height: 40px;vertical-align: middle;background-color: #f0f0f0;padding-left:20px; color:#ff7000;font-size:16px;'><a name='qt'></a>其他</li><li style=''>---输入内容---</li></ul></div>";

  $scope.onSelectChange = function(){
    for (var i=0;i<$scope.supplierListOfProduct.length;i++){
      if($scope.supplierListOfProduct[i]['id'] == $scope.product.pAccessId){
        $scope.accessNameOfCompany = $scope.supplierListOfProduct[i]['accessName'];
        break;
      }
    }
  };

  $scope.save = function(){
    if (!$scope.form.$invalid){
      $scope.selectTjzls = [];
      var flag = false;
      for (var i in $scope.allTjzls){
        if ($scope.allTjzls[i]){
           flag = true;
           $scope.selectTjzls.push(i);
        }
      }
      if (!flag){
        alert("请勾选提交资料");
        return;
      }
      $scope.product.id = "";
      //新增pe/vc 产品
      $scope.product.pType = "06";
      //$scope.product.pIssuingScale = $scope.product.pIssuingScaleTmp * 100000000;
      $scope.product.pIssuingScale = 0;

      $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale * 100000000;
      $scope.product.pProgressiveAmount = $scope.product.pProgressiveAmountTmp * 10000;
      $scope.product.pMinimumAmount = $scope.product.pMinimumAmountTmp * 10000;

      if($scope.ct && $scope.report.id){
        $scope.product.copyType = "01";
      }
      $scope.product.tjzls=$scope.selectTjzls.join(",");
      productService.productAddPEVC($scope.product).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          //产品录入成功之后，如果是复制操作则把年化佣金、附件同时保存到数据库。
          if($scope.pid != undefined && $scope.pid.length > 0){
            if($scope.projectAnnualRevenue.length > 0 && $scope.projectRabateList.length > 0){
              $scope.formData = {pId:[],pRebateType:[],pStartAmount:[],pEndAmount:[],pAnnualRevenueExpect:[],pIsAgreement:[],pRabateProfit:[],pCorePrice:[],pCostPrice:[],pSellingPrice:[],pCostBackPrice:[],pCoreBackPrice:[],pBackSellingPrice:[],pBackRabateProfit:[]};
              angular.forEach($scope.projectAnnualRevenue,function(o,i){
                //产品ID
                $scope.formData['pId'].push(json.projectDTO.id);
                //返佣类型，01：百分比
                $scope.formData['pRebateType'].push("01");
                //起始金额
                $scope.formData['pStartAmount'].push(o['pStartAmount']);
                // 结束金额
                $scope.formData['pEndAmount'].push(o['pEndAmount']);
                // 预期年化率
                $scope.formData['pAnnualRevenueExpect'].push(o['pAnnualRevenueExpect']);
                // 返佣率
                $scope.formData['pRabateProfit'].push($scope.projectRabateList[i]['pRabateProfit'] || 0);
                // 核心价
                $scope.formData['pCorePrice'].push($scope.projectRabateList[i]['pCorePrice'] || 0);
                // 成本价
                $scope.formData['pCostPrice'].push($scope.projectRabateList[i]['pCostPrice'] || 0);
                // 机构价
                $scope.formData['pSellingPrice'].push($scope.projectRabateList[i]['pSellingPrice'] || 0);

                $scope.formData['pCostBackPrice'].push($scope.projectRabateList[i]['pCostBackPrice'] || 0);
                $scope.formData['pCoreBackPrice'].push($scope.projectRabateList[i]['pCoreBackPrice'] || 0);
                $scope.formData['pBackSellingPrice'].push($scope.projectRabateList[i]['pBackSellingPrice'] || 0);
                $scope.formData['pBackRabateProfit'].push($scope.projectRabateList[i]['pBackRabateProfit'] || 0);
                // 是否协议
                $scope.formData['pIsAgreement'].push($scope.projectRabateList[i]['pIsAgreement']);
              });
              $scope.formData2 = {id:json.projectDTO.id};
              for (k in $scope.formData){
                $scope.formData2[k] = $scope.formData[k].join(",");
              }
              productService.productProfitUpdate($scope.formData2).then(function(json){
                if (json.statusCode){
                  alert("保存年化及佣金时，出错了:" + json.statusCode);
                }
              });
            }
            
            if($scope.attachs.length > 0){
              // 保存附件的数据
              $scope.formDataAttach = {fName:[],fileUrl:[],fileType:[]};
              angular.forEach($scope.attachs,function(o,i){
                if (o['fName'] && o['fPath'] && o['fType']){
                  $scope.formDataAttach['fName'].push(o['fName']);
                  $scope.formDataAttach['fileUrl'].push(o['fPath']);
                  $scope.formDataAttach['fileType'].push(o['fType']);
                }
              });
              $scope.formData2Attach = {pId:json.projectDTO.id};
              for (k in $scope.formDataAttach){
                $scope.formData2Attach[k] = $scope.formDataAttach[k].join(",");
              }
              productService.productAttachUpdate($scope.formData2Attach).then(function(json){
                if (json.statusCode){
                  alert("保存附件时，出错了:" + json.statusCode);
                }
              });
            }

            // 如果选择复制 产品解析报告，则在此处先加载原产品的解析报告
            if($scope.ct && $scope.report.id){
              delete $scope.report.id;
              $scope.report.fpProductId = json.projectDTO.id;
              $scope.report.fpProductStatus = "2";
              reportService.deepAnalyticsSave($scope.report).then(function(json){
                if (json.statusCode){
                  alert("出错了:" + json.statusCode);
                }
              });
            }
          }
          $scope.alertNextPage("产品录入成功!");
          $location.path("/pevcproduct/edit").search({id:json.projectDTO.id,t:$scope.t});
        }
      });
    }else{
      if ($scope.product.pSummary == undefined || !$scope.product.pSummary){
        alert("请填写产品简介");
      }else alert("请完整填写表单");
    }
  };

  $scope.onUploadFile({
      showMessage : function(m){ alert(m); },
      onComplete:function(f,response,id){
        id--;
        if (response.statusCode == "0000") {
          if(id==0){
             $scope.product.pImageUri = response.attribute.fileUrl;
           }else if(id==1){
            $scope.product.peLogoUri= response.attribute.fileUrl;
           }else if(id==2){
            $scope.product.peHomeLogoUri= response.attribute.fileUrl;
           }
          $scope.$apply();
        } else { 
          alert('上传失败'); 
        }
      }    
  });
}]);


faApp.controller('PEVCProductBaseInfoCtrl',['$scope','productService','supplierService','$location','$controller','$routeParams','$filter','companyService','$route',function($scope,productService,supplierService,$location,$controller,$routeParams,$filter,companyService,$route) {   
  $controller('BaseCtrl', {$scope: $scope});

  $scope.product = {};
  $scope.loading = true; 
  $scope.pathText = "修改产品";
  $scope.id = $routeParams.id;
  $scope.pPublicAreaModel = $scope.publicAreaModel;
  if ($scope.pPublicAreaModel[0].value != "00")$scope.pPublicAreaModel.unshift({value:"00",text:"全国"}); 
  $scope.companys = [];
  $scope.companysMap = {};

  companyService.companyList().then(function(json){
    $scope.companys = json.list;
    angular.forEach($scope.companys,function(o){
      $scope.companysMap[o.id] = o;
    });
  });

  $scope.supplierListOfProduct = [];
  $scope.queryAccessCompany="";
  $scope.$watch('queryAccessCompany',function(){
     supplierService.supplierList({accessCompany:$scope.queryAccessCompany}).then(function(json){
        $scope.supplierListOfProduct = json.list;
      });
  },true);
  $scope.allTjzls = {};
  productService.productQuery($scope.id).then(function(json){
    $scope.product = json.project;
    if($scope.product.tjzls!=undefined){
      angular.forEach($scope.product.tjzls.split(","),function(o){
      $scope.allTjzls[o] = true;  
    }); 
    }
    $scope.product.pIssuingScaleTmp = $scope.product.pIssuingScale / 100000000;
    $scope.product.pProgressiveAmountTmp = $scope.product.pProgressiveAmount / 10000;
    $scope.product.pMinimumAmountTmp = $scope.product.pMinimumAmount / 10000;
    $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale / 100000000;
    $scope.product.pSaleTimeStartStr = $filter("date")($scope.product.pSaleTimeStart,"yyyy-MM-dd");
    $scope.product.image = $scope.product.pImageUri;
    $scope.accessNameOfCompany = $scope.product.pAccessName;

    if($scope.product.tjzls!=undefined){
      angular.forEach($scope.product.tjzls.split(","),function(o){
        $scope.allTjzls[o] = true;  
      }); 
    }
    if($scope.product.projectExpandDTO!=undefined){
      //PE/VC新增扩展字段
    $scope.product.peManageOrg=$scope.product.projectExpandDTO.peManageOrg;
    $scope.product.peOrganizeShape=$scope.product.projectExpandDTO.peOrganizeShape;
    $scope.product.peFundShape=$scope.product.projectExpandDTO.peFundShape;
    $scope.product.peSubscriptionFee=$scope.product.projectExpandDTO.peSubscriptionFee;
    $scope.product.peManagementExpense=$scope.product.projectExpandDTO.peManagementExpense;
    $scope.product.peLogoUri=$scope.product.projectExpandDTO.peLogoUri;
    $scope.product.peHomeLogoUri=$scope.product.projectExpandDTO.peHomeLogoUri;
    $scope.product.peRevenueSharing=$scope.product.projectExpandDTO.peRevenueSharing;
    $scope.product.peCompanyDescription=$scope.product.projectExpandDTO.peCompanyDescription;
    delete $scope.product.projectExpandDTO;
    }
    

    delete $scope.product.pSaleTimeStart;
    delete $scope.product.pSaleTimeEnd;
    delete $scope.product.pEstablishmentTime;
    delete $scope.product.pCode;

    $scope.t = $scope.product.pType;

    $scope.loading = false;
  });

  $scope.onSelectChange = function(){
    for (var i=0;i<$scope.supplierListOfProduct.length;i++){
      if($scope.supplierListOfProduct[i]['id'] == $scope.product.pAccessId){
        $scope.accessNameOfCompany = $scope.supplierListOfProduct[i]['accessName'];
        break;
      }
    }
  };
  
  $scope.save = function(){
    if (!$scope.form.$invalid){
      $scope.selectTjzls = [];
      var flag = false;
      for (var i in $scope.allTjzls){
        if ($scope.allTjzls[i]){
           flag = true;
           $scope.selectTjzls.push(i);
        }
      }
      if (!flag){
        alert("请勾选提交资料");
        return;
      }
      $scope.product.pIssuingScale = $scope.product.pIssuingScaleTmp * 100000000;
      $scope.product.pProgressiveAmount = $scope.product.pProgressiveAmountTmp * 10000;
      $scope.product.pMinimumAmount = $scope.product.pMinimumAmountTmp * 10000;
      $scope.product.pAllIssuingScale = $scope.product.pAllIssuingScale * 100000000;

      if ($scope.product.pSizeRatioType && ($scope.product.pSizeRatioExplain == undefined || $scope.product.pSizeRatioExplain == "")){
        $scope.product.pSizeRatioExplain = $filter("pSizeRatioTypeRender")($scope.product.pSizeRatioType);
      }
      $scope.product.tjzls=$scope.selectTjzls.join(",");
      productService.productUpdatePEVC($scope.product).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("产品修改成功!");
          $route.reload();
        }
      });
    }else{
      if (!$scope.product.pSummary){
        alert("请填写产品简介");
      }else alert("请完整填写表单");
    }
  };
 
  $scope.onUploadFile({
      showMessage : function(m){ alert(m); },
      onComplete:function(f,response,id){
        id--;
        if (response.statusCode == "0000") {
          if(id==0){
             $scope.product.pImageUri = response.attribute.fileUrl;
           }else if(id==1){
            $scope.product.peLogoUri= response.attribute.fileUrl;
           }else if(id==2){
            $scope.product.peHomeLogoUri= response.attribute.fileUrl;
           }
          $scope.$apply();
        } else { 
          alert('上传失败'); 
        }
      }    
  });

  $scope.selectInvestOwner = function(){
    $scope.product.pInvestOwner = $scope.product.pInvestOwnerId == undefined ? $scope.companysMap[$scope.product.pInvestOwnerId]['cShortName'] : "";
  };
  
  $scope.changePsizeRatioType = function(){
    if ($scope.product.pSizeRatioType){
      $scope.product.pSizeRatioExplain = $filter("pSizeRatioTypeRender")($scope.product.pSizeRatioType);
    }
  };
}]);


faApp.controller('PEVCProductEditCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','companyService','sessionService',function($scope,productService,$location,$controller,$routeParams,$filter,companyService,sessionService) {   
  $scope.id = $routeParams.id;
  $scope.t = $routeParams.t;
  $scope.tabUrl = {};
  $scope.tabUrlMap = {
    viewUrl : "#/pevcproduct/view?id=" + $scope.id,
    baseUrl : "#/pevcproduct/baseInfo?id=" + $scope.id,
    saleprocessUrl: "#/pevcproduct/saleProcess?id=" + $scope.id,
    profitUrl : "#/product/profit?id=" + $scope.id,
    attachmentUrl : "#/product/attach?id=" + $scope.id,
    roadVideo : "#/product/video?id=" + $scope.id,
  };
  
  $scope.changeTab = function(tab){
    $scope.tabUrl[tab] = $scope.tabUrlMap[tab];
    sessionService.setItem("lastProductTab",tab);
  };
  
  var lastProductTab = sessionService.getItem('lastProductTab') || 'viewUrl'; 
  $scope.changeTab('viewUrl');
  
  $scope.pathText = $scope.id ? "修改产品" : "新建产品"; 
  
  angular.element(document).ready(function(){
    // console.log(1);
    if ($(window).height() > 300) $scope.iframeHeight = $(window).height() - 130;
  });

}]);

faApp.controller('PEVCProductViewCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','userService','$route',function($scope,productService,$location,$controller,$routeParams,$filter,userService,$route) {   
  $controller('ProductBaseCtrl', {$scope: $scope}); 
  $scope.id = $routeParams.id;
  $scope.projectAnnualRevenue = [];
  $scope.projectRabateList = [];

  productService.productQuery($scope.id).then(function(json){
    $scope.project = json.project;
    $scope.projectAnnualRevenue = json.projectAnnualRevenueList;
    $scope.projectRabateList = json.projectRabateList; 
    console.log($scope.projectRabateList);
  });
  
  $scope.userList = [];
  userService.userList().then(function(json){
    $scope.userRawList = json.list || [];
    angular.forEach($scope.userRawList,function(o){
      if (o.userNickname != $scope.loginStatus.loginName){
        $scope.userList.push(o);
      }
    });
    
  });
  $scope.transList = [];
  productService.transPermissionList({pProjectId:$scope.id,pageSize:1000}).then(function(json){
    $scope.transList = json.list || [];
  });
  $scope.trans = {pProjectId:$scope.id};
  $scope.save = function(){
    if (!$scope.form.$invalid){
      productService.transPermissionAdd($scope.trans).then(function(json){
        if (json.statusCode){
          alert("出错了:" + json.statusCode);
        }else{
          $scope.alertNextPage("操作成功");
          parent.location.href = parent.location.href;
          //$route.reload();
        }
      });
    }else{
      alert("请先完整填写表单");
    }
  };
}]);

faApp.controller('PEVCProductSaleProcessCtrl',['$scope','productService','$location','$controller','$routeParams','$filter','$route',function($scope,productService,$location,$controller,$routeParams,$filter,$route) {   
  $controller('BaseCtrl', {$scope: $scope}); 
  $scope.id = $routeParams.id;
  $scope.item = {id:$scope.id};
  $scope.loading = true;
  productService.productQuery($scope.id).then(function(json){
   
    $scope.project = json.project;
    $scope.item.pAllSubscriptionAmountTmp = json.project.pAllSubscriptionAmount/10000;
    $scope.item.pIssuingScale = json.project.pIssuingScale / 10000;
    $scope.item.pRecruitmentSummary = json.project.pRecruitmentSummary;
    $scope.item.pSaleStatus = json.project.pSaleStatus;
    $scope.item.pAllSubscriptionNum = json.project.pAllSubscriptionNum?json.project.pAllSubscriptionNum:0;
    // $scope.item.pSizeRatioType = json.project.pSizeRatioType;
    // $scope.item.pSizeRatioExplain = json.project.pSizeRatioExplain;
     $scope.item.pPeriods = json.project.pPeriods;
      $scope.loading = false; 
  });

  $scope.changePsizeRatioType = function(){
    if ($scope.item.pSizeRatioType){
      $scope.item.pSizeRatioExplain = $filter("pSizeRatioTypeRender")($scope.item.pSizeRatioType);
    }
  };

  $scope.save = function(){
    if($scope.item.pAllSubscriptionAmountTmp > $scope.item.pIssuingScale){
      alert("已销售总额不能大于单期规模！");
      return;
    }
    if($scope.item.pIssuingScale > ($scope.project.pAllIssuingScale/10000)){
      alert("单期规模不能大于发行规模！");
      return;
    }
    $scope.item.pAllSubscriptionAmount = $scope.item.pAllSubscriptionAmountTmp * 10000;
    $scope.item.pIssuingScale = $scope.item.pIssuingScale * 10000;
    productService.updateSaleProcess($scope.item).then(function(json){
      if (json.statusCode){
        alert("出错了:" + json.statusCode);
      }else{
        productService.updateRecruitmentProcess($scope.item).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }  
        });
        
        productService.productEdit($scope.item).then(function(json){
          if (json.statusCode){
            alert("出错了:" + json.statusCode);
          }else{
            $scope.alertNextPage("产品修改成功!");
            $route.reload();
          }
        });
      }
    });
  };
}]);